package logic

import (
	"context"
	"fmt"
	"muke-chain/models/cache"
	"muke-chain/models/mysql"
	"muke-chain/pkg"

	"muke-chain/mukerpc/internal/svc"
	"muke-chain/mukerpc/mukerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterUserLogic {
	return &RegisterUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterUserLogic) RegisterUser(in *mukerpc.RegisterUserRequest) (*mukerpc.RegisterUserResponse, error) {
	// todo: add your logic here and delete this line

	get := cache.Rdb.Get(l.ctx, "sendSms"+"register"+in.Mobile)
	if get.Val() != in.Sms {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}

	var userFind mysql.Users
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&userFind)
	if userFind.ID != 0 {
		return nil, fmt.Errorf("该号已被注册,请前往登录")
	}

	user := mysql.Users{
		Mobile:   in.Mobile,
		Password: pkg.Md5(in.Password),
	}
	err := mysql.DB.Debug().Create(&user).Error
	if err != nil {
		return nil, fmt.Errorf("注册失败")
	}

	cache.Rdb.Del(l.ctx, "sendSms"+"register"+in.Mobile)
	return &mukerpc.RegisterUserResponse{Id: int64(user.ID)}, nil
}
